<template>
    <el-dialog :model-value="dialogVisible" :before-close="handleClose" title="新增机构" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
            <!-- 机构名称 -->
            <el-form-item label="机构名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>

            <!-- 选择省份 -->
            <!-- <el-form-item label="选择省份" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off" />
            </el-form-item> -->
            <el-form-item label="选择省份" :label-width="formLabelWidth" prop="city">
                <el-cascader :options="citys" @change="changeSelectCity" v-model="selectCity" placeholder="选择城市"
                    clearable />
            </el-form-item>

            <!-- 所属地区 -->
            <el-form-item label="所属地区" :label-width="formLabelWidth" prop="address">
                <el-input v-model="form.address" autocomplete="off" />
            </el-form-item>

            <!-- 管理员名称 -->
            <el-form-item label="管理员名称" :label-width="formLabelWidth" prop="adminName">
                <el-input v-model="form.adminName" autocomplete="off" />
            </el-form-item>

            <!-- 联系电话 -->
            <el-form-item label="联系电话" :label-width="formLabelWidth" prop="telephone">
                <el-input v-model="form.telephone" autocomplete="off" />
            </el-form-item>

            <div v-if="props.changeId == 0">
                <!-- 管理员账号 -->
                <el-form-item label="管理员账号" :label-width="formLabelWidth" prop="adminUserName">
                    <el-input v-model="form.adminUserName" autocomplete="off" />
                </el-form-item>

                <!-- 密码 -->
                <el-form-item label="密码" :label-width="formLabelWidth" prop="adminPwd">
                    <el-input v-model="form.adminPwd" autocomplete="off" />
                </el-form-item>
            </div>


        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="changeParent(false)">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">{{ props.changeId==0?'添加':'修改' }}</el-button>
                <!-- <el-button type="primary" @click="dialogVisible = false">
                    Confirm
                </el-button> -->
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang='ts'>
import { addCompany, getCity, getCompany } from '@/apis/branch/branch';
import type { cityData, Company, CompanyAdd } from '@/apis/branch/type';
import { doEncrypt } from '@/utils/cryptoUtil';
import { number } from 'echarts';
import { ElMessage, ElMessageBox, type ComponentSize, type FormInstance, type FormRules } from 'element-plus';
import { ref, reactive, watch, onMounted, onUpdated } from 'vue';

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    changeParent: {
        type: Function,
        default: () => { }
    },
    changeId: {
        type: Number,
        default: 0
    }
})



const emit = defineEmits(['closeDialog'])
const close = () => {
    emit('closeDialog', false)
}

// 获取单条机构信息
const getCompanyById = async (id: number) => {
    let res = await getCompany(id)
    console.log('单条机构信息', res);
    form.value = res
}

 
onUpdated(() => {
    if(props.changeId == 0){
        form.value = {
        name: '',
        address: '',
        adminUserName: '',
        adminMobile: '',
        adminName: '',
        adminPwd: '',
        telephone: '',
        city: '',
        province: '',
        id: 0
    }
    selectCity.value = []
    }

    if (props.changeId != 0) {
        getCompanyById(props.changeId)
    }
})




// 点击遮罩层关闭弹窗的函数
const handleClose = (done: () => void) => {
    props.changeParent(false)
    close();
    
    form.value = {
        name: '',
        address: '',
        adminUserName: '',
        adminMobile: '',
        adminName: '',
        adminPwd: '',
        telephone: '',
        city: '',
        province: '',
        id: 0
    }
    selectCity.value = []


}


// 获取城市数据
// 获取城市
interface City {
    value: string;
    label: string;
    children: { value: string; label: string; }[]
}
let options: cityData[] = []
let citys = ref<City[]>([])
const getCityLIst = async () => {
    let res = await getCity()
    // console.log('城市', res);
    // 确保 res 是数组类型，并进行类型断言
    if (Array.isArray(res)) {
        options = res as cityData[];
        // console.log(options);
        options.forEach(item => {
            citys.value.push({
                value: item.n,
                label: item.n,
                children: item.c.map(city => ({
                    value: city.n,
                    label: city.n
                }))
            })
        })
        // console.log('循环', citys);
    } else {
        console.error("返回数据不是数组类型", res);
        options = []; // 如果不是数组，初始化为空数组避免错误
    }
}
getCityLIst()
// 存储选中的城市
let selectCity = ref<string[]>([])
const changeSelectCity = (selectCity: string[]) => {
    // console.log(selectCity);
    if (selectCity) {
        form.value.city = selectCity[0]
        form.value.province = selectCity[1]
        // console.log(selectCity);
    }
}

// 输入框宽度
const formLabelWidth = '140px'

// 添加表单
const formRef = ref<FormInstance | null>(null);
const ruleFormRef = ref<FormInstance>()
const form = ref<Company>({
    name: '',
    address: '',
    adminUserName: '',
    adminMobile: '',
    adminName: '',
    adminPwd: '',
    telephone: '',
    city: '',
    province: '',
    id: 0
})



// 添加表单

const rules = reactive<FormRules<Company>>({
    name: [
        { required: true, message: '请输入机构名称', trigger: 'blur' },
    ],
    address: [
        { required: true, message: '请输入所属地址', trigger: 'blur' },
    ],
    adminName: [
        { required: true, message: '请输入管理员姓名', trigger: 'blur' },

    ],
    telephone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
    ],
    adminPwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    adminUserName: [
        { required: true, message: '请输入管理员账号', trigger: 'blur' },

    ],
    city: [
        { required: true, message: '请输选择城市', trigger: 'blur' },
    ],
})



// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) {
        ElMessage.error('表单未正确初始化，请刷新页面重试');
        return
    }

    console.log(form.value);
    await formEl.validate(async (valid: boolean) => {
        if (valid) {

            // 加密密码
            form.value.adminPwd = await doEncrypt(form.value.adminPwd as string);

            let res = await addCompany(form.value)
            // console.log('账号添加',res);

            ElMessage.success(props.changeId==0 ? '账号添加成功':'账号修改成功');
            // 关闭弹窗
            props.changeParent(false);

            // 清空表单数据
            form.value = {
                name: '',
                address: '',
                adminUserName: '',
                adminMobile: '',
                adminName: '',
                adminPwd: '',
                telephone: '',
                city: '',
                province: '',
                id: 0
            };
            selectCity.value = [];

            close();


        } else {
            console.log('error submit!!');
            // 不需要返回 false，直接结束函数即可
        }
    });
};






</script>

<style scoped lang='less'></style>